"""
下载JavaScript库文件到本地
"""
import requests
import os
from pathlib import Path

# 设置代理（如果需要）
proxies = {
    # 'http': 'http://127.0.0.1:8894',
    # 'https': 'http://127.0.0.1:8894'
}

# JavaScript库下载列表
js_libs = [
    {
        'name': 'lightweight-charts.min.js',
        'url': 'https://unpkg.com/lightweight-charts@4.1.0/dist/lightweight-charts.standalone.production.js'
    },
    {
        'name': 'apexcharts.min.js', 
        'url': 'https://cdn.jsdelivr.net/npm/apexcharts@3.44.0/dist/apexcharts.min.js'
    },
    {
        'name': 'plotly-2.27.0.min.js',
        'url': 'https://cdn.plot.ly/plotly-2.27.0.min.js'
    }
]

# 创建目录
js_dir = Path('web_ui/static/js')
js_dir.mkdir(parents=True, exist_ok=True)

print("开始下载JavaScript库文件...")

for lib in js_libs:
    file_path = js_dir / lib['name']
    
    # 如果文件已存在，跳过
    if file_path.exists():
        print(f"✅ {lib['name']} 已存在，跳过下载")
        continue
    
    print(f"正在下载 {lib['name']}...")
    try:
        # 尝试不使用代理下载
        response = requests.get(lib['url'], timeout=30)
        response.raise_for_status()
        
        # 保存文件
        with open(file_path, 'wb') as f:
            f.write(response.content)
        
        file_size = len(response.content) / 1024 / 1024  # MB
        print(f"✅ {lib['name']} 下载成功 ({file_size:.2f} MB)")
        
    except requests.exceptions.ProxyError:
        print(f"❌ {lib['name']} 下载失败：代理错误，尝试不使用代理...")
        try:
            response = requests.get(lib['url'], timeout=30, proxies={})
            response.raise_for_status()
            with open(file_path, 'wb') as f:
                f.write(response.content)
            file_size = len(response.content) / 1024 / 1024
            print(f"✅ {lib['name']} 下载成功 ({file_size:.2f} MB)")
        except Exception as e:
            print(f"❌ {lib['name']} 下载失败：{e}")
    except Exception as e:
        print(f"❌ {lib['name']} 下载失败：{e}")

print("\n下载完成！")

# 创建CSS目录
css_dir = Path('web_ui/static/css')
css_dir.mkdir(parents=True, exist_ok=True)

print("\n目录结构创建完成！")
print("web_ui/static/")
print("├── js/")
for lib in js_libs:
    file_path = js_dir / lib['name']
    if file_path.exists():
        print(f"│   ├── {lib['name']}")
print("└── css/")